#include "Zuma.h"
#include "ZumaThread.h"
using namespace std;


int finishingDrawing = 1;
int done = 0;
int drawThreadDelay = 5;
int moveThreadDelay = 52;

int stageDraw(void *data);
int moveElements(void *data);


Zuma::Zuma(void){
	this->logger = LogFactory::getInstance()->getLog();
}

Zuma::~Zuma(void){
	if(this->stages != NULL){
		this->stages->clear();
		delete this->stages;
	}
	delete DaoFactory::getInstance();
	delete General::getInstance();
}

void Zuma::startStage( Stage * stage )
{
		
	stage->initialize();
	
	ZumaThread *drawThread = new ZumaThread(stageDraw,stage);
	drawThread->runForest();
	
	ZumaThread *moveThread = new ZumaThread(moveElements,stage);
	//moveThread->runForest();

	SDL_Event  evt;
	done = 0;
				
	while(done == 0){

		while(SDL_PollEvent(&evt)){
			if(evt.type == SDL_KEYDOWN){
				done = 1;
				while(finishingDrawing){
					SDL_Delay(100);
				}
			}
			if(evt.type == SDL_QUIT){
				done = 1;
				while(finishingDrawing){
					SDL_Delay(100);
				}
			}
			if(evt.type == SDL_MOUSEBUTTONDOWN){
				Position *position = SketcherHelper::getInstance()->getPositionMeasurementUnit(new Position(evt.button.x,evt.button.y));
				delete position;
			}
		}
	}
}

int moveElements(void *data){
	
	Stage *stage = (Stage* )data;
	
	while (done == 0) {
		/*Quizas aki habria que invocar un stage->draw que a su vez vaya 
		llamando a los draw de los objetos movibles*/
		SketcherHelper::getInstance()->clearBackground(stage->getFrog()->getMainBall()->getPosition(),stage->getFrog()->getMainBall()->getRadius()*2,stage->getFrog()->getMainBall()->getRadius()*2);
		stage->getFrog()->getMainBall()->move();
		SDL_Delay(moveThreadDelay);
	}
	return 0;
}

int stageDraw(void *data){

	Stage *stage = (Stage* )data;
	finishingDrawing = 1;
	cout << "thread I Running " <<endl;
	
	LogFactory::getInstance()->getLog()->info("Thread I starts");
	while (done == 0){
		stage->draw();
		SDL_Delay(drawThreadDelay);
	}
	finishingDrawing = 0;
	LogFactory::getInstance()->getLog()->info("Thread I ends");
	return 0;
}

list<Stage *> * Zuma::getStages( void ){
	return this->stages;
}

void Zuma::setStages( list<Stage *> * stages ){
	this->stages = stages;
}